package com.ooono.factorytest.items;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.ooono.factorytest.R;
import com.ooono.factorytest.base.BaseActivity;

import java.util.List;

public class WifiTestActivity extends BaseActivity {

    private static final String TAG = "WifiTestActivity";

    public static final String KEY = "wifi";

    private WifiManager mWifiManager;
    private WifiReceiver mWifiReceiver;

    private List<ScanResult> mWifiList;

    private TextView wifiTestResultTv;

    private String wifiResult;

    @Override
    public int getTestTitle() {
        return R.string.test_item_wifi;
    }

    @Override
    public String getTestKey() {
        return KEY;
    }

    @Override
    public int getContentLayout() {
        return R.layout.content_wifi_test;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        mWifiReceiver = new WifiReceiver();
        wifiResult = getResources().getString(R.string.wifi_test_prompt);
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        registerReceiver(mWifiReceiver, filter);

        mWifiManager.setWifiEnabled(true);
        wifiResult += "\n open wifi";
        wifiTestResultTv.setText(wifiResult);
    }

    @Override
    public void initViews() {
        wifiTestResultTv = findViewById(R.id.tv_wifi_test_result);
    }

    private void connectWifi(String ssid) {
        WifiConfiguration wifiConfiguration = new WifiConfiguration();
        wifiConfiguration.SSID = "\"" + ssid + "\"";
        wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        int id = mWifiManager.addNetwork(wifiConfiguration);
        WifiInfo connectionInfo = mWifiManager.getConnectionInfo();
        mWifiManager.disableNetwork(connectionInfo.getNetworkId());
        boolean b = mWifiManager.enableNetwork(id, true);
        Log.d(TAG, "connectWifi: 连接状态=" + b);
        if (b) {
            mWifiManager.saveConfiguration();
        } else {
            Log.d(TAG, wifiConfiguration.toString());
        }
    }

    class WifiReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {
                int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
                if (state == WifiManager.WIFI_STATE_ENABLED) {
                    Log.e(TAG, "wifi is open");
                    wifiResult += "\n wifi is open";
                    wifiTestResultTv.setText(wifiResult);
                    // 2、开始扫描
                    mWifiList = mWifiManager.getScanResults();
                    Log.e(TAG, "wifi start scan");
                    wifiResult += "\n wifi start scan...";
                    wifiTestResultTv.setText(wifiResult);
                }
            } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
                // 监听wifi连接状态
                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                if (NetworkInfo.State.DISCONNECTED == info.getState()) {
                    // wifi没连接上
                    Log.e(TAG, "连接状态：wifi没连接上");
                } else if (NetworkInfo.State.CONNECTED == info.getState()) {
                    // wifi连接上了
                    Log.d(TAG, "wifi ");
                    wifiResult += "\n wifi connected";
                    wifiTestResultTv.setText(wifiResult);
                }
            } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent.getAction())) {
                wifiResult += "\n wifi scan complete";
                wifiTestResultTv.setText(wifiResult);

                if (!mWifiList.isEmpty()) {
                    // 不为空时， 开始操作列表
                    Log.d(TAG, ">> 搜索到 " + mWifiList.size() + "个热点");
                    wifiResult += "\n " + mWifiList.size() + " hotspots found on WiFi";
                    wifiTestResultTv.setText(wifiResult);
                    mWifiList.forEach(scanResult -> {
                        if (!scanResult.capabilities.contains("WEP") && !scanResult.capabilities.contains("PSK") && !scanResult.capabilities.contains("EAP")) {
                            String ssid;
                            if (TextUtils.isEmpty(scanResult.SSID)) {
                                ssid = scanResult.BSSID;
                            } else {
                                ssid = scanResult.SSID;
                            }
                            Log.d(TAG, ">> 搜索到 " + mWifiList.size() + "个热点");
                            // 这个热点是没有加密的
                            Log.d(TAG, ssid + " 这个热点是没有加密的...");
                            connectWifi(ssid);
                        }
                    });
                }
            }
        }
    }
}
